const fs = require('fs');
const path = require('path');
const pm2 = require('pm2');
const { app, BrowserWindow, clipboard, dialog, Menu, Tray } = require('electron');

// 获取单例锁
const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  app.quit();
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    let current = BrowserWindow.getAllWindows()[0];

    if (current && (current.isMaximized() || !current.isVisible())) {
      current.show();
    }
  });
}

let popMenu = Menu.buildFromTemplate([
  {
    label: '复制',
    click: (item, event) => {
      let current = BrowserWindow.getFocusedWindow();

      current.webContents.copy();

      let copyedText = (clipboard.readText('clipboard') || '').replace(/[\n\r\s\v]/ig, '');

      clipboard.writeText(copyedText, 'clipboard');
    }
  },
  {
    type: 'separator'
  },
  {
    label: '刷新页面',
    click: (item, event) => {
      let win = BrowserWindow.getAllWindows()[0];

      win.reload();
    }
  },
  {
    type: 'separator'
  },
  {
    label: '打开调试窗口',
    click: () => {
      let win = BrowserWindow.getAllWindows()[0];

      if (win) {
        win.maximize();
        win.show();
        win.webContents.openDevTools();
      }
    }
  }
]);

app.on('browser-window-created', (event, win) => {
  win.webContents.on('context-menu', (e, params) => {
    popMenu.popup({ window: win, x: params.x, y: params.y });
  });
});

app.commandLine.appendSwitch('lang', 'zh-CN');

let rootPath = app.getAppPath();

const pm2Config = {
  name: 'monitor',
  script: path.resolve(rootPath, 'app.js'),
  exec_mode: 'cluster',
  instances: 2,
  max_memory_restart: '200M',
  shutdown_with_message: true,
  env: {
    PORT: 8881,
    ROOT: rootPath
  }
};

function createWindow () {
  const win = new BrowserWindow({
    width: 1024,
    height: 800,
    show: true,
    center: true,
    titleBarStyle: 'hiddenInset',
    webPreferences: {
      nodeIntegration: true,
      nodeIntegrationInWorker: true
    },
    autoHideMenuBar: true,
    icon: path.resolve(rootPath, 'wwwroot', 'favicon.ico')
  });

  win.maximize();
  win.loadFile(path.resolve(rootPath, 'loading.html'));

  // 关闭按钮处理
  win.on('close', e => {
    win.hide();
    e.preventDefault();
  });

  // 最小化处理
  win.on('minimize', () => {
    win.hide();
  });

  pm2.connect(function (err) {
    if (err) {
      fs.writeFileSync(path.resolve(rootPath, 'error.log'), err);

      process.exit(0);
    }

    pm2.start(pm2Config,
      function (err, apps) {
        if (err) {
          fs.writeFileSync(path.resolve(rootPath, 'error.log'), err);

          process.exit(0);
        }

        win.loadURL(`http://localhost:${pm2Config.env.PORT}`).then(() => { }).catch(err => win.reload());
      });
  });
}

let tray = null;
let isInExiting = false;

app.whenReady().then(() => {
  tray = new Tray(path.resolve(rootPath, 'wwwroot', 'favicon.ico'));

  const contextMenu = Menu.buildFromTemplate([
    {
      label: '刷新页面', click: (item, event) => {
        let win = BrowserWindow.getAllWindows()[0];

        win.maximize();
        win.reload();
      }
    },
    {
      label: '显示主界面',
      click: () => {
        let win = BrowserWindow.getAllWindows()[0];

        if (win) {
          win.maximize();
          win.show();
        }
      }
    },
    {
      type: 'separator'
    },
    {
      label: '打开调试窗口',
      click: () => {
        let win = BrowserWindow.getAllWindows()[0];

        if (win) {
          win.maximize();
          win.show();
          win.webContents.openDevTools();
        }
      }
    },
    {
      label: '重新加载应用...',
      click: () => {
        let win = BrowserWindow.getAllWindows()[0];

        pm2.reload('monitor', () => {
          win.reload();
        });
      }
    },
    {
      type: 'separator'
    },
    {
      label: '退出',
      click: exitQuestion
    }
  ]);

  tray.setToolTip('个人辅助系统');
  tray.setContextMenu(contextMenu);
  tray.on('click', () => {
    if(isInExiting) {
      return;
    }
  
    let win = BrowserWindow.getAllWindows()[0];

    if (win) {
      win.maximize();
      win.show();
    }
  });

  createWindow();
});

app.on('ready', () => {
  Menu.setApplicationMenu(null);
});

app.on('browser-window-created', (event, currentWin) => {
  currentWin.maximize();
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length == 0) {
    createWindow();
  }
});

app.setUserTasks([]);

/**
 * 退出&提醒
 */
function exitQuestion (e) {
  let win = BrowserWindow.getAllWindows()[0];

  win.show();

  let index = dialog.showMessageBoxSync(win, {
    type: 'question',
    title: '提示',
    defaultId: 1,
    message: '确定要关闭吗？',
    buttons: ['取消', '确定']
  });

  if (index == 0) {
    if (e && e.preventDefault) { e.preventDefault(); }
  } else {
    isInExiting = true;
    tray.setContextMenu(Menu.buildFromTemplate([{ label: '退出中...' }]));
    tray.setToolTip('正在退出中，请稍候...');

    if (pm2) {
      win.hide();

      pm2.stop('monitor', () => {
        pm2.killDaemon(() => {
          win.close();
          app.quit();
          process.exit(0);
        });
      });

      return;
    }

    win.close();
    app.quit();
    process.exit(0);
  }
}